<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>考试详情</span>
          <div>
            <el-button type="primary" @click="editExam">编辑</el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>

      <div v-loading="loading" class="exam-detail">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h3>基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="18">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="考试标题">{{ examInfo.title }}</el-descriptions-item>
                <el-descriptions-item label="考试类型">{{ getExamTypeText(examInfo.type) }}</el-descriptions-item>
                <el-descriptions-item label="考试状态">
                  <el-tag :type="getStatusTagType(examInfo.status)">
                    {{ getStatusText(examInfo.status) }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="关联课程">{{ examInfo.courseName || '无' }}</el-descriptions-item>
                <el-descriptions-item label="考试时长">{{ examInfo.duration }} 分钟</el-descriptions-item>
                <el-descriptions-item label="总分">{{ examInfo.totalScore }} 分</el-descriptions-item>
                <el-descriptions-item label="及格分">{{ examInfo.passScore }} 分</el-descriptions-item>
                <el-descriptions-item label="最大尝试次数">{{ examInfo.maxAttempts || '无限制' }}</el-descriptions-item>
                <el-descriptions-item label="开始时间">{{ formatDateTime(examInfo.startTime) }}</el-descriptions-item>
                <el-descriptions-item label="结束时间">{{ formatDateTime(examInfo.endTime) }}</el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ formatDateTime(examInfo.createTime) }}</el-descriptions-item>
                <el-descriptions-item label="更新时间">{{ formatDateTime(examInfo.updateTime) }}</el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col :span="6">
              <div class="exam-actions">
                <el-button 
                  v-if="examInfo.status === 'DRAFT'" 
                  type="success" 
                  @click="publishExam"
                  :loading="publishing"
                >
                  发布考试
                </el-button>
                <el-button 
                  v-if="examInfo.status === 'PUBLISHED'" 
                  type="warning" 
                  @click="pauseExam"
                  :loading="pausing"
                >
                  暂停考试
                </el-button>
                <el-button 
                  v-if="examInfo.status === 'PAUSED'" 
                  type="primary" 
                  @click="resumeExam"
                  :loading="resuming"
                >
                  恢复考试
                </el-button>
                <el-button 
                  v-if="['PUBLISHED', 'PAUSED'].includes(examInfo.status)" 
                  type="danger" 
                  @click="endExam"
                  :loading="ending"
                >
                  结束考试
                </el-button>
                <el-button @click="copyExam" :loading="copying">
                  复制考试
                </el-button>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 考试描述 -->
        <div class="detail-section" v-if="examInfo.description">
          <h3>考试描述</h3>
          <div class="description-content">
            {{ examInfo.description }}
          </div>
        </div>

        <!-- 考试设置 -->
        <div class="detail-section">
          <h3>考试设置</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="题目顺序">{{ getQuestionOrderText(examInfo.questionOrder) }}</el-descriptions-item>
            <el-descriptions-item label="允许迟到">{{ examInfo.allowLateEntry ? '是' : '否' }}</el-descriptions-item>
            <el-descriptions-item label="显示分数">{{ examInfo.showScore ? '是' : '否' }}</el-descriptions-item>
            <el-descriptions-item label="显示答案">{{ examInfo.showAnswer ? '是' : '否' }}</el-descriptions-item>
            <el-descriptions-item label="允许回顾">{{ examInfo.allowReview ? '是' : '否' }}</el-descriptions-item>
            <el-descriptions-item label="防作弊">{{ examInfo.antiCheat ? '是' : '否' }}</el-descriptions-item>
            <el-descriptions-item label="摄像头监控">{{ examInfo.cameraMonitor ? '是' : '否' }}</el-descriptions-item>
            <el-descriptions-item label="屏幕录制">{{ examInfo.screenRecord ? '是' : '否' }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 题型配置 -->
        <div class="detail-section" v-if="examInfo.questionTypes && examInfo.questionTypes.length > 0">
          <h3>题型配置</h3>
          <el-table :data="examInfo.questionTypes" style="width: 100%">
            <el-table-column prop="type" label="题型" width="150">
              <template #default="scope">
                {{ getQuestionTypeText(scope.row.type) }}
              </template>
            </el-table-column>
            <el-table-column prop="count" label="题目数量" width="120" />
            <el-table-column prop="score" label="每题分数" width="120" />
            <el-table-column label="小计分数" width="120">
              <template #default="scope">
                {{ scope.row.count * scope.row.score }}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 统计信息 -->
        <div class="detail-section">
          <h3>统计信息</h3>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-statistic title="参与人数" :value="statistics.participantCount || 0" />
            </el-col>
            <el-col :span="6">
              <el-statistic title="完成人数" :value="statistics.completedCount || 0" />
            </el-col>
            <el-col :span="6">
              <el-statistic title="平均分" :value="statistics.averageScore || 0" :precision="1" />
            </el-col>
            <el-col :span="6">
              <el-statistic title="及格率" :value="statistics.passRate || 0" suffix="%" :precision="1" />
            </el-col>
          </el-row>
        </div>

        <!-- 最近考试记录 -->
        <div class="detail-section">
          <h3>最近考试记录</h3>
          <el-table :data="recentRecords" style="width: 100%">
            <el-table-column prop="studentName" label="学生姓名" width="120" />
            <el-table-column prop="score" label="得分" width="100" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getRecordStatusTagType(scope.row.status)">
                  {{ getRecordStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="duration" label="用时" width="100">
              <template #default="scope">
                {{ formatDuration(scope.row.duration) }}
              </template>
            </el-table-column>
            <el-table-column prop="submitTime" label="提交时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.submitTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button type="text" size="small" @click="viewRecord(scope.row)">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getExamDetail, 
  getExamStatistics,
  publishExam as publishExamApi,
  pauseExam as pauseExamApi,
  resumeExam as resumeExamApi,
  endExam as endExamApi,
  copyExam as copyExamApi,
  getExamRecordPage
} from '@/api/exam'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(true)
const publishing = ref(false)
const pausing = ref(false)
const resuming = ref(false)
const ending = ref(false)
const copying = ref(false)
const examInfo = ref({})
const statistics = ref({})
const recentRecords = ref([])

// 获取考试详情
const loadExamDetail = async () => {
  try {
    const response = await getExamDetail(route.params.id)
    if (response.code === 200) {
      examInfo.value = response.data
    }
  } catch (error) {
    console.error('获取考试详情失败:', error)
    ElMessage.error('获取考试详情失败')
  }
}

// 获取考试统计
const loadExamStatistics = async () => {
  try {
    const response = await getExamStatistics(route.params.id)
    if (response.code === 200) {
      statistics.value = response.data
    }
  } catch (error) {
    console.error('获取考试统计失败:', error)
  }
}

// 获取最近考试记录
const loadRecentRecords = async () => {
  try {
    const response = await getExamRecordPage({ 
      examId: route.params.id, 
      pageSize: 10,
      current: 1 
    })
    if (response.code === 200) {
      recentRecords.value = response.data.records || []
    }
  } catch (error) {
    console.error('获取考试记录失败:', error)
  }
}

// 编辑考试
const editExam = () => {
  router.push(`/exam/exam/edit/${route.params.id}`)
}

// 返回列表
const goBack = () => {
  router.push('/exam/exam')
}

// 发布考试
const publishExam = async () => {
  try {
    await ElMessageBox.confirm('确定要发布这个考试吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    publishing.value = true
    const response = await publishExamApi(route.params.id)
    if (response.code === 200) {
      ElMessage.success('考试发布成功')
      await loadExamDetail()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发布考试失败:', error)
      ElMessage.error('发布考试失败')
    }
  } finally {
    publishing.value = false
  }
}

// 暂停考试
const pauseExam = async () => {
  try {
    await ElMessageBox.confirm('确定要暂停这个考试吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    pausing.value = true
    const response = await pauseExamApi(route.params.id)
    if (response.code === 200) {
      ElMessage.success('考试暂停成功')
      await loadExamDetail()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('暂停考试失败:', error)
      ElMessage.error('暂停考试失败')
    }
  } finally {
    pausing.value = false
  }
}

// 恢复考试
const resumeExam = async () => {
  try {
    resuming.value = true
    const response = await resumeExamApi(route.params.id)
    if (response.code === 200) {
      ElMessage.success('考试恢复成功')
      await loadExamDetail()
    }
  } catch (error) {
    console.error('恢复考试失败:', error)
    ElMessage.error('恢复考试失败')
  } finally {
    resuming.value = false
  }
}

// 结束考试
const endExam = async () => {
  try {
    await ElMessageBox.confirm('确定要结束这个考试吗？结束后将无法恢复。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    ending.value = true
    const response = await endExamApi(route.params.id)
    if (response.code === 200) {
      ElMessage.success('考试结束成功')
      await loadExamDetail()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('结束考试失败:', error)
      ElMessage.error('结束考试失败')
    }
  } finally {
    ending.value = false
  }
}

// 复制考试
const copyExam = async () => {
  try {
    const { value: title } = await ElMessageBox.prompt('请输入新考试的标题', '复制考试', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValue: `${examInfo.value.title} - 副本`
    })
    
    copying.value = true
    const response = await copyExamApi(route.params.id, title)
    if (response.code === 200) {
      ElMessage.success('考试复制成功')
      router.push(`/exam/exam/detail/${response.data.id}`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('复制考试失败:', error)
      ElMessage.error('复制考试失败')
    }
  } finally {
    copying.value = false
  }
}

// 查看考试记录
const viewRecord = (record) => {
  router.push(`/exam/record/detail/${record.id}`)
}

// 工具函数
const getExamTypeText = (type) => {
  const typeMap = {
    'QUIZ': '测验',
    'EXAM': '考试',
    'PRACTICE': '练习',
    'ASSIGNMENT': '作业'
  }
  return typeMap[type] || '未知'
}

const getStatusText = (status) => {
  const statusMap = {
    'DRAFT': '草稿',
    'PUBLISHED': '已发布',
    'PAUSED': '已暂停',
    'ENDED': '已结束'
  }
  return statusMap[status] || '未知'
}

const getStatusTagType = (status) => {
  const typeMap = {
    'DRAFT': 'info',
    'PUBLISHED': 'success',
    'PAUSED': 'warning',
    'ENDED': 'danger'
  }
  return typeMap[status] || 'info'
}

const getQuestionOrderText = (order) => {
  const orderMap = {
    'FIXED': '固定顺序',
    'RANDOM': '随机顺序'
  }
  return orderMap[order] || '固定顺序'
}

const getQuestionTypeText = (type) => {
  const typeMap = {
    'SINGLE_CHOICE': '单选题',
    'MULTIPLE_CHOICE': '多选题',
    'TRUE_FALSE': '判断题',
    'FILL_BLANK': '填空题',
    'SHORT_ANSWER': '简答题',
    'ESSAY': '论述题'
  }
  return typeMap[type] || '未知'
}

const getRecordStatusText = (status) => {
  const statusMap = {
    'IN_PROGRESS': '进行中',
    'SUBMITTED': '已提交',
    'GRADED': '已评分',
    'TIMEOUT': '超时'
  }
  return statusMap[status] || '未知'
}

const getRecordStatusTagType = (status) => {
  const typeMap = {
    'IN_PROGRESS': 'warning',
    'SUBMITTED': 'primary',
    'GRADED': 'success',
    'TIMEOUT': 'danger'
  }
  return typeMap[status] || 'info'
}

const formatDateTime = (datetime) => {
  if (!datetime) return '未设置'
  return new Date(datetime).toLocaleString()
}

const formatDuration = (duration) => {
  if (!duration) return '0分钟'
  const hours = Math.floor(duration / 60)
  const minutes = duration % 60
  return hours > 0 ? `${hours}小时${minutes}分钟` : `${minutes}分钟`
}

// 页面加载
onMounted(async () => {
  loading.value = true
  try {
    await Promise.all([
      loadExamDetail(),
      loadExamStatistics(),
      loadRecentRecords()
    ])
  } finally {
    loading.value = false
  }
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.exam-detail {
  .detail-section {
    margin-bottom: 32px;
    
    h3 {
      margin-bottom: 16px;
      color: #303133;
      border-bottom: 2px solid #409eff;
      padding-bottom: 8px;
    }
  }
  
  .exam-actions {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  
  .description-content {
    line-height: 1.6;
    white-space: pre-wrap;
    padding: 16px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }
}
</style>
